Page({
  data: {
    name: '',
    phone: '',
    region: '',
    detail: '',
    isDefault: false,
    isEdit: false,
    id: null,
    regionArray: ['', '', ''] // 省市区数组
  },
  
  onLoad(options) {
    if (options.id) {
      const addresses = wx.getStorageSync('addresses') || []
      const address = addresses.find(a => a.id === parseInt(options.id))
      if (address) {
        // 解析地区字符串为数组
        const regionArray = this.parseRegion(address.region)
        this.setData({
          isEdit: true,
          id: address.id,
          name: address.name,
          phone: address.phone,
          region: address.region,
          detail: address.detail,
          isDefault: address.isDefault || false,
          regionArray: regionArray
        })
      }
    }
  },
  
  // 解析地区字符串为数组（格式：省市区）
  parseRegion(regionStr) {
    if (!regionStr) return ['', '', '']
    // 尝试按省、市、区/县分割
    let province = '', city = '', district = ''
    
    // 匹配省
    const provinceMatch = regionStr.match(/^(.+?省)/)
    if (provinceMatch) {
      province = provinceMatch[1]
      regionStr = regionStr.substring(province.length)
    }
    
    // 匹配市
    const cityMatch = regionStr.match(/^(.+?市)/)
    if (cityMatch) {
      city = cityMatch[1]
      regionStr = regionStr.substring(city.length)
    }
    
    // 匹配区或县
    const districtMatch = regionStr.match(/^(.+?[区县])/)
    if (districtMatch) {
      district = districtMatch[1]
    } else if (regionStr) {
      // 如果没有区县标识，但还有剩余文字，也当作区
      district = regionStr
    }
    
    return [province, city, district]
  },
  
  onNameInput(e) {
    this.setData({ name: e.detail.value })
  },
  
  onPhoneInput(e) {
    this.setData({ phone: e.detail.value })
  },
  
  // 地区选择改变
  onRegionChange(e) {
    const values = e.detail.value
    const regionArray = values
    // 将省市区数组拼接成字符串（过滤空值）
    const region = regionArray.filter(item => item).join('')
    
    this.setData({
      regionArray: regionArray,
      region: region
    })
  },
  
  onDetailInput(e) {
    this.setData({ detail: e.detail.value })
  },
  
  toggleDefault() {
    this.setData({
      isDefault: !this.data.isDefault
    })
  },
  
  save() {
    if (!this.data.name || !this.data.phone || !this.data.region || !this.data.detail) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }
    
    let addresses = wx.getStorageSync('addresses') || []
    
    if (this.data.isDefault) {
      // 取消其他默认地址
      addresses = addresses.map(a => ({ ...a, isDefault: false }))
    }
    
    if (this.data.isEdit) {
      const index = addresses.findIndex(a => a.id === this.data.id)
      if (index !== -1) {
        addresses[index] = {
          id: this.data.id,
          name: this.data.name,
          phone: this.data.phone,
          region: this.data.region,
          detail: this.data.detail,
          isDefault: this.data.isDefault
        }
      }
    } else {
      const newId = addresses.length > 0 ? Math.max(...addresses.map(a => a.id)) + 1 : 1
      addresses.push({
        id: newId,
        name: this.data.name,
        phone: this.data.phone,
        region: this.data.region,
        detail: this.data.detail,
        isDefault: this.data.isDefault
      })
    }
    
    wx.setStorageSync('addresses', addresses)
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    })
    
    setTimeout(() => {
      wx.navigateBack()
    }, 1500)
  },
  
  delete() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          let addresses = wx.getStorageSync('addresses') || []
          addresses = addresses.filter(a => a.id !== this.data.id)
          wx.setStorageSync('addresses', addresses)
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      }
    })
  }
})


